<template>
  <el-dialog :title="currentObj?'编辑分类':'添加分类'" :visible.sync="showDialog_" custom-class='dialog_right MkAddCategory' top="0%" @close='closeDialog("addForm")' @open='openDialog'>
    <el-form :model="addForm.formItem" :rules="addForm.rules" ref="addForm" label-width="80px">
      <input type="text" style="display:none" />
      <el-form-item label="分类名称" prop='name'>
        <el-input v-model.trim="addForm.formItem.name" placeholder='请输入分类名称（必填）' size="" :maxlength=7></el-input>
      </el-form-item>
      <el-form-item label="排序" prop='sort'>
        <el-input v-model.trim="addForm.formItem.sort" placeholder='请输入排序（必填）' size="" :maxlength=7></el-input>
      </el-form-item>
      <el-form-item label="上级分类" v-if="parentObj">
        {{parentObj.name}}
      </el-form-item>
      <el-form-item label="上级分类" v-if="currentObj && currentObj.parentName">
        {{currentObj.parentName}}
      </el-form-item>
      <el-form-item label="分类图片" prop="imageId">
        <el-upload class="avatar-uploader"
                   :action=" '/upload/images.json'"
                   list-type="picture-card"
                   :on-success="handleSuccess"
                   :on-remove="handleRemove"
                   :file-list="fileList"
                   :before-upload="beforeCoverUpload"
                   accept=".jpeg, .jpg, .png, .gif"
                   name="images">
          <!--<img v-if="imageUrl" :src="imageUrl" class="avatar">-->
          <i class="el-icon-plus avatar-uploader-icon"></i>
        </el-upload>

        <!--:data="{width:600,height:600}"-->
      </el-form-item>
      <el-form-item label="是否展示" prop='status'>
        <el-radio-group v-model="addForm.formItem.status">
          <el-radio label="ENABLE">是</el-radio>
          <el-radio label="DISABLE">否</el-radio>
        </el-radio-group>
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer footerStyle">
      <el-button type="primary" class='btn-primary' :disabled="isSubmitBtnDisabled" @click='submitForm("addForm")' v-loading.fullscreen.lock="fullscreenLoading">保存</el-button>
      <el-button type='primary' class='btn-cancel' @click="showDialog_ = false" size=''>取消</el-button>
    </div>
  </el-dialog>
</template>

<script>
import productService from '../../services/product'
export default {
  name: 'MkAddCategory',
  components: {

  },
  props: ['showDialog', 'parentObj', 'currentObj'],
  computed: {
  },
  methods: {
    handleRemove(file, fileList) {
      this.fileList = fileList;
      let fileId = file.fileId ? file.fileId : file.response.data[0].fileId;
      productService.deleteFileServer({ fileId: fileId }, data => {
        this.$message.success('删除成功');
        this.addForm.formItem.imageId = '';
      })
    },
    beforeCoverUpload() {

    },
    handleSuccess(res, fileList) {
      this.fileList = [fileList];
    },
    closeDialog(formName) {
      this.$refs[formName].resetFields();
      this.$emit('closeDialog', this.isRefresh);
      var form = this.addForm.formItem;
      form.name = '';
      form.status = 'ENABLE';
      form.imageId = '';
      form.parentId = '';
      form.id = '';
      form.sort = 99;
      this.fileList = [];
    },
    openDialog() {
      this.isRefresh = false;
      this.isSubmitBtnDisabled = false;
      if (this.currentObj) {
        var form = this.addForm.formItem;
        var currentObj = this.currentObj;
        form.name = currentObj.name;
        form.status = currentObj.status;
        form.id = currentObj.id;
        form.sort = currentObj.weight;
        if (currentObj.image) {
          form.imageId = currentObj.image.fileId;
          this.fileList = [{ url: currentObj.image.accessUrl, fileId: currentObj.image.fileId }];
        }
      }
    },
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if (!this.currentObj) {
            this.addForm.formItem.parentId = this.parentObj ? this.parentObj.id : 1;
          }
          let fileArr = [];
          for(var i = 0 ;i<this.fileList.length;i++) {
            let file = this.fileList[i];
            fileArr.push(file.fileId ? file.fileId : file.response.data[0].fileId);
          }
          this.addForm.formItem.imageId = fileArr.join(',');

          this.fullscreenLoading = true;
          this.isSubmitBtnDisabled = true;
          if (this.currentObj) {
            productService.editCategoryServer(this.addForm.formItem, (data) => {
              this.$message.success('编辑成功');
              this.isRefresh = true;
              this.showDialog_ = false;
              this.fullscreenLoading = false;
            }, (data) => {
              this.fullscreenLoading = false;
              this.isSubmitBtnDisabled = false;
            })
          } else {
            productService.addCategoryServer(this.addForm.formItem, (data) => {
              this.$message.success('添加成功');
              this.isRefresh = true;
              this.showDialog_ = false;
              this.fullscreenLoading = false;
            }, (data) => {
              this.fullscreenLoading = false;
              this.isSubmitBtnDisabled = false;
            })
          }
        }
      })
    }
  },
  watch: {
    showDialog: function(value) {
      this.showDialog_ = value;
    }
  },
  data() {
      let checkName = (rule, val, callback) => {
        if (val === '') {
          callback('请输入分类名称');
        } else {
          if(val.length > 7) {
            callback('最多输入7个字符');
          }else{
            callback();
          }
        }
      };
      let checkSort = (rule, value, callback) => {
        if (value === '') {
          callback('请输入排序');
        } else {
          let reg = /(^0$|^[1-9]\d*$)/;
          if(!reg.test(value)){
              callback('请输入数字');
          }else{
              callback();
          }
        }
      };
    return {
      fileList: [],
      isSubmitBtnDisabled: false,
      fullscreenLoading: false,
      isRefresh: false,
      showDialog_: this.showDialog,
      addForm: {
        formItem: {
          name: '',
          status: 'ENABLE',
          imageId: '',
          parentId: '',
          sort:'99',

          id: ''//编辑用到
        },
        rules: {
          name:{validator:checkName,trigger:'change'},
          sort:{validator:checkSort,trigger:'change'},
        }
      }

    }
  }
}
</script>
<!-- Add "scoped" attribute to limit CSS to this component only -->
<style lang='less'>
@import '../../assets/style/main.less';
.MkAddCategory {
  .avatar-uploader {
    .el-upload-list--picture-card {
      position: absolute;
      z-index: 10;
    }
    .el-upload:hover {
      border-color: @primaryColor;
    }
    .el-upload {
      border: 1px dashed #d9d9d9;
      border-radius: 6px;
      cursor: pointer;
      position: relative;
      overflow: hidden;
      height: 146px;
      width: 146px;
    }
    .el-upload--picture-card {
      background: white;
    }
    .avatar-uploader-icon {
      font-size: 28px;
      color: #8c939d;
      width: 146px;
      height: 146px;
      line-height: 146px;
      text-align: center;
    }
  }
}
</style>
